package com.tanhua.common.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.common.config.AliyunConfig;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Service
public class PicUploadService {

    private static final String[] IMAGE_TYPE = new String[]{".bmp",".jpg",".jpeg",".gif",".png"};

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;

    public PicUploadResult upload(MultipartFile uploadFile){
        PicUploadResult fileUploadResult = new PicUploadResult();

        //后缀名校验
        boolean isLegal = false;

        for (String type : IMAGE_TYPE) {
            if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }

        if(!isLegal){
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }

        //新路径
        String filename = uploadFile.getOriginalFilename();
        String filePath = getFilePath(filename);

        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filePath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }


        //上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));

        return fileUploadResult;

    }

    private String getFilePath(String filename) {
        DateTime dateTime = new DateTime();
        return "images/"+dateTime.toString("yyyy")+"/"+dateTime.toString("MM")+"/"+dateTime.toString("dd")+"/"
                +System.currentTimeMillis()+ RandomUtils.nextInt(100,9999)+"."+StringUtils.substringAfterLast(filename,".");
    }
}
